<template>
    <div>
        <Form :label-width="80" ref="formInline" :model="dataToQuery">
            <Row :gutter="16" class="query-form2" >
                <i-col span="8">
                    <FormItem label="年份：" prop="year">
                        <DatePicker type="year" v-model="dataToQuery.yearDate" format="yyyy" placeholder="请选择年份" style="width:100%"></DatePicker>
                    </FormItem>
                </i-col>
                <i-col span="16">
                    <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                    </div>
                </i-col>
            </Row>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
            </i-col>
        </Row>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading'
               border :columns="columns1"  :data="dataTable" ></Table>
        <Row type="flex" justify="end" >
            <i-col>
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>
        <Modal v-model="modal1" width="800" :mask-closable="false" title="国家法定节假日编辑">
            <div :style="{height: divHeight, overflowY: 'auto', overflowX: 'hidden'}">
                <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
                    <Row>
                        <i-col span="24">
                            <FormItem label="年度：" prop="year">
                                <DatePicker type="year" v-model="formData.year" format="yyyy" placeholder="请选择年份" style="width:100%"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="元旦假期：" prop="newYear">
                                <DatePicker  type="daterange" placeholder="清选择元旦假期" style="width: 98%" v-model="formData.newYear"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="元旦倒班：" prop="newYearShifts">
                                <DatePicker type="date" placeholder="清选择元旦倒班" style="width: 98%" multiple v-model="formData.newYearShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="春节假期：" prop="springFestival">
                                <DatePicker type="daterange" placeholder="清选择春节假期" style="width: 98%" v-model="formData.springFestival"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="春节倒班：" prop="springFestivalShifts">
                                <DatePicker type="date" placeholder="清选择春节倒班" style="width: 98%" multiple v-model="formData.springFestivalShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="清明节假期：" prop="qingMingFestival">
                                <DatePicker type="daterange" placeholder="请选择清明节假期" style="width: 98%" v-model="formData.qingMingFestival"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="清明节倒班：" prop="qingMingShifts">
                                <DatePicker type="date" placeholder="清选择清明节倒班" style="width: 98%" multiple v-model="formData.qingMingShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="劳动节假期：" prop="laborDay">
                                <DatePicker type="daterange" placeholder="请选择劳动节假期" style="width: 98%" v-model="formData.laborDay"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="劳动节倒班" prop="laborDayShifts">
                                <DatePicker type="date" placeholder="清选择劳动节倒班" style="width: 98%" multiple v-model="formData.laborDayShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="端午节假期：" prop="dragonBoatFestival">
                                <DatePicker type="daterange" placeholder="请选择端午节假期" style="width: 98%" v-model="formData.dragonBoatFestival"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="端午节倒班：" prop="dragonBoatShifts">
                                <DatePicker type="date" placeholder="清选择端午节倒班" style="width: 98%" multiple v-model="formData.dragonBoatShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="中秋节假期：" prop="midAutumnFestival">
                                <DatePicker type="daterange" placeholder="请选择中秋节假期" style="width: 98%" v-model="formData.midAutumnFestival"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="中秋节倒班：" prop="midAutumnShifts">
                                <DatePicker type="date" placeholder="清选择中秋节倒班" style="width: 98%" multiple v-model="formData.midAutumnShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="国庆节假期：" prop="nationalDay">
                                <DatePicker type="daterange" placeholder="请选择国庆节假期" style="width: 98%" v-model="formData.nationalDay"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="24">
                            <FormItem label="国庆节倒班：" prop="nationalDayShifts">
                                <DatePicker type="date" placeholder="请选择国庆节倒班" style="width: 98%" multiple v-model="formData.nationalDayShifts"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <div slot="footer">
                <Button @click="saveInfo" class="ivu-btn-save">确定</Button>
                <Button @click="modal1 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '@/api/index.js'

    export default {
        name: "holidayConfig",
        data(){
            return {
                ...this.createCommonDataField(),
                isUpdate: false,
                divHeight: '',
                tableHeight: '',
                columns1: [
                    {
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                        render: this.indexColumnsRender
                    },
                    {
                        title: '年份',
                        align: 'center',
                        key: 'year',
                        minWidth: 80,
                        render: (h, params) => {
                            let date = new Date(params.row.year);
                            return h('div', [
                                (date.getFullYear())
                            ]);
                        }
                    },

                    {
                        title: '创建人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 80,
                    },
                    {
                        title: '创建时间',
                        align: 'center',
                        key: 'createDate',
                        minWidth: 160,
                        render: this.renderCellDate
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        minWidth: 120,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.status == "1" || params.row.status == "2" || params.row.status == "3"? '#d0d0d0' : '',
                                        pointerEvents: params.row.status == "1" || params.row.status == "2" || params.row.status == "3"? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.isUpdate = true;
                                            this.updateRow(params.row);
                                            this.modal1 = true;
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red',
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteRow(params.row);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    }
                ],
                infos: [],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                pageSizeArray: [10, 20, 50],
                modal1: false,
                formData: {},
                ruleCustom: {
                    year: [{required: true,message: '  ',trigger: 'blur,change', type: 'date' }],
                    newYear: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    springFestival: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    springFestivalShifts: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            if(value.findIndex(target=>target=== false) == 0){
                                callback(' ');
                            }else{
                                callback();
                            }
                        }
                    }],
                    qingMingFestival: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    laborDay: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    laborDayShifts: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            if(value.findIndex(target=>target=== false) == 0){
                                callback(' ');
                            }else{
                                callback();
                            }
                        }
                    }],
                    dragonBoatFestival: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    midAutumnFestival: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    nationalDay: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            let r = true;
                            value.forEach(i =>{
                                if(i == '')
                                    r = false;
                            })
                            if(r) callback()
                            else callback(' ');
                        }
                    }],
                    nationalDayShifts: [{required: true,message: '  ',trigger: 'blur,change',
                        validator: (rule, value, callback) => {
                            if(value.findIndex(target=>target=== false) == 0){
                                callback(' ');
                            }else{
                                callback();
                            }
                        }
                    }]
                },
                queryUrl: Api.queryYearHoliday,
                deleteUrl: Api.deleteYearHoliday,
                editYear: '',
            }
        },
        mounted(){
            this.divHeight = window.innerHeight - 150 +'px';
            this.setTableHeight();
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            query(){
                if(this.dataToQuery.yearDate != ''&&this.dataToQuery.yearDate != undefined){
                    this.dataToQuery.year = this.dataToQuery.yearDate.getFullYear();
                }
                this.queryAjax();
            },
            cancel(){
                this.dataToQuery = {};
                this.query();
            },
            indexColumnsRender(h, params){
                return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            addInfo(){
                this.modal1 = true;
                this.isUpdate = false;
            },
            updateRow(row){
                let data = {
                    id: row.id,
                    year: new Date(row.year),
                    newYear: this.getEitdDateArray(row.newYear),
                    springFestival: this.getEitdDateArray(row.springFestival),
                    qingMingFestival: this.getEitdDateArray(row.qingMingFestival),
                    laborDay: this.getEitdDateArray(row.laborDay),
                    dragonBoatFestival: this.getEitdDateArray(row.dragonBoatFestival),
                    midAutumnFestival: this.getEitdDateArray(row.midAutumnFestival),
                    nationalDay: this.getEitdDateArray(row.nationalDay),
                    springFestivalShifts: this.getEitdDateArrayAll(row.springFestivalShifts),
                    laborDayShifts: this.getEitdDateArrayAll(row.laborDayShifts),
                    nationalDayShifts: this.getEitdDateArrayAll(row.nationalDayShifts),
                    newYearShifts: row.newYearShifts!= null ? this.getEitdDateArrayAll(row.newYearShifts): null,
                    qingMingShifts: row.qingMingShifts != null?  this.getEitdDateArrayAll(row.qingMingShifts): null,
                    dragonBoatShifts: row.dragonBoatShifts? this.getEitdDateArrayAll(row.dragonBoatShifts): null,
                    midAutumnShifts: row.midAutumnShifts? this.getEitdDateArrayAll(row.midAutumnShifts): null,
                };
                this.editYear = new Date(row.year).getFullYear();
                this.formData = data;
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        console.log(this.formData.midAutumnShifts);
                        let data = {
                            id: this.formData.id,
                            year: this.formData.year,
                            newYear: this.getDateArray(this.formData.newYear),
                            springFestival: this.getDateArray(this.formData.springFestival),
                            qingMingFestival: this.getDateArray(this.formData.qingMingFestival),
                            laborDay: this.getDateArray(this.formData.laborDay),
                            dragonBoatFestival: this.getDateArray(this.formData.dragonBoatFestival),
                            midAutumnFestival: this.getDateArray(this.formData.midAutumnFestival),
                            nationalDay: this.getDateArray(this.formData.nationalDay),
                            springFestivalShifts: this.getDateToString(this.formData.springFestivalShifts),
                            laborDayShifts: this.getDateToString(this.formData.laborDayShifts),
                            nationalDayShifts: this.getDateToString(this.formData.nationalDayShifts),
                            newYearShifts: this.formData.newYearShifts!= null && this.formData.newYearShifts[0] != false ? this.getDateToString(this.formData.newYearShifts): null,
                            qingMingShifts: this.formData.qingMingShifts != null && this.formData.qingMingShifts[0] != false?  this.getDateToString(this.formData.qingMingShifts): null,
                            dragonBoatShifts: this.formData.dragonBoatShifts && this.formData.dragonBoatShifts[0] != false ? this.getDateToString(this.formData.dragonBoatShifts): null,
                            midAutumnShifts: this.formData.midAutumnShifts != null && this.formData.midAutumnShifts[0] != false ? this.getDateToString(this.formData.midAutumnShifts): null,
                            createUserId: sessionStorage('userId').getObject('userId').userId,
                            updateUserId: sessionStorage('userId').getObject('userId').userId,
                        };
                        console.log(data);
                        if(this.isUpdate){
                            if(this.editYear == this.formData.year.getFullYear()){
                                this.$http.put(Api.updateYearHoliday, data).then(function(response){
                                    this.modal1 = false;
                                    if(response.data.status == 200){
                                        this.$Message.success({ content: '保存成功', duration: 4 });
                                        this.query();
                                    }else{
                                        this.$Message.error({ content: response.data.msg, duration: 4 });
                                    }
                                });
                            }else{
                                this.$http.get(Api.getYearHoliday + 'year', {params : {year: data.year.getFullYear()}}).then(function(response){
                                    if(response.data.data == 0){
                                        this.$http.put(Api.updateYearHoliday, data).then(function(response){
                                            this.modal1 = false;
                                            if(response.data.status == 200){
                                                this.$Message.success({ content: '保存成功', duration: 4 });
                                                this.query();
                                            }else{
                                                this.$Message.error({ content: response.data.msg, duration: 4 });
                                            }
                                        });
                                    }else{
                                        this.$Message.error({ content: '当前年已配置，请勿重复保存', duration: 4 });
                                    }
                                });
                            }
                        }else{
                            this.$http.get(Api.getYearHoliday + 'year', {params : {year: data.year.getFullYear()}}).then(function(response){
                                if(response.data.data == 0){
                                    this.$http.post(Api.saveYearHoliday, data).then(function(response){
                                        // this.modal1 = false;
                                        if(response.data.status == 200){
                                            this.$Message.success({ content: '保存成功', duration: 4 });
                                            this.query();
                                        }else{
                                            this.$Message.error({ content: response.data.msg, duration: 4 });
                                        }
                                    });
                                }else{
                                    this.$Message.error({ content: '当前年已配置，请勿重复保存', duration: 4 });
                                }
                            });
                        }
                    }
                });
            },
            getDateArray(arr){
                let start = arr[0];
                let end = arr[1];
                const resultTime = [];
                while (start <= end) {
                    let getDay = start.getDate()
                    // 月份需要加 1
                    let getMonth = start.getMonth() + 1
                    let getYear = start.getFullYear()
                    /**
                     * 拼接时间格式
                     * (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) 自动给 小于10的时间前面补0
                     */
                    let setTime =
                        `${getYear}-` +
                        (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) +
                        '-' +
                        (getDay >= 10 ? `${getDay}` : `0${getDay}`)

                    resultTime.push(setTime);
                    start = new Date(start.setFullYear(getYear, getMonth - 1, getDay + 1))
                }
                return resultTime.join(',');
            },
            getDateToString(arr){
                const resultTime = [];
                arr.forEach(i=>{
                    let getDay = i.getDate()
                    let getMonth = i.getMonth() + 1
                    let getYear = i.getFullYear()
                    let setTime =
                        `${getYear}-` +
                        (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) +
                        '-' +
                        (getDay >= 10 ? `${getDay}` : `0${getDay}`)
                    resultTime.push(setTime);
                })
                return resultTime.join(',');
            },
            getEitdDateArray(str){
                let arr = str.split(',');
                return [new Date(arr[0]), new Date(arr[arr.length-1])];
            },
            getEitdDateArrayAll(str){
                let arr = str.split(',');
                let dateArray = [];
                arr.map(i=>{
                    dateArray.push(new Date(i));
                })
                return dateArray;
            },
            deleteRow(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.deleteYearHoliday + row.id).then((res) => {
                            this.$Message.success({content:'删除成功',duration: 4});
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
        }
    }
</script>

<style scoped>

</style>
